<template>
  <div class="navbar">
    <div class="left">
      <NButton text class="bold" @click="goHome"> nuxt3 demo </NButton>
      <NMenu :options="menuOptions" mode="horizontal" :value="activeKey" />
    </div>
    <div class="right">
      <n-icon size="30" @click="showDrawer" class="icon1">
        <SearchCircleOutline />
      </n-icon>

      <div v-if="!user" @click="goLogin">登录</div>
      <n-dropdown
        v-else
        trigger="hover"
        :options="options"
        @select="handleSelect"
      >
        <n-image
          width="30"
          style="border-radius: 50%"
          :src="
            user.avatar ||
            'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'
          "
        />
      </n-dropdown>
    </div>
  </div>

  <SearchBar ref="searchRef" />
</template>

<script setup lang="ts">
import type { MenuOption } from "naive-ui";
import { RouterLink } from "vue-router";
import {
  NButton,
  NMenu,
  NIcon,
  NImage,
  NDropdown,
  createDiscreteApi,
} from "naive-ui";
import { SearchCircleOutline } from "@vicons/ionicons5";

const route = useRoute();
const user = useUser();

// 菜单
const renderRouter = (opts: { key: string; name: string; to: any }) => {
  return {
    key: opts.key,
    label: () => h(RouterLink, { to: opts.to }, { default: () => opts.name }),
  };
};
const arr = [
  {
    key: "/",
    name: "首页",
    to: { path: "/" },
  },
  {
    key: "/paper/1",
    name: "考试",
    to: {
      name: "paper-id",
      params: {
        id: 1,
      },
    },
  },
  // 同一种ui样式
  {
    key: "/list/group/1",
    name: "拼团",
    to: {
      name: "list-type-page", // 目录-拼接
      params: {
        // 多个参数
        type: "group",
        page: 1,
      },
    },
  },
  {
    key: "/list/flashsale/1",
    name: "秒杀",
    to: {
      name: "list-type-page",
      params: {
        type: "flashsale",
        page: 1,
      },
    },
  },
  {
    key: "/list/live/1",
    name: "直播",
    to: {
      name: "list-type-page",
      params: {
        type: "live",
        page: 1,
      },
    },
  },
  {
    key: "/list/column/1",
    name: "专栏",
    to: {
      name: "list-type-page",
      params: {
        type: "column",
        page: 1,
      },
    },
  },
  // 另外一种ui样式
  {
    key: "/list/book/1",
    name: "电子书",
    to: {
      name: "list-type-page",
      params: {
        type: "book",
        page: 1,
      },
    },
  },
  {
    key: "/bbs/0/1",
    name: "社区",
    to: {
      name: "bbs-bbs_id-page",
      params: {
        bbs_id: 0,
        page: 1,
      },
    },
  },
  {
    key: "/list/course/1",
    name: "课程",
    to: {
      name: "list-type-page",
      params: {
        type: "course",
        page: 1,
      },
    },
  },
];
const menuOptions: MenuOption[] = arr.map((v) => renderRouter(v));
// TODO:高亮判断优化
const activeKey = computed(() => {
  // console.log(route.name, route.params);
  // 1 name 、params都匹配（params匹配是因为有分页为2的情况，且参数为多个的时候）
  // 2 或者path匹配
  const pathItem = arr.find((v) => v.to.path === route.path);
  if (pathItem) {
    return pathItem.key;
  }
  if (route.name === "list-type-page") {
    return arr.find((v) => v.to.params?.type === route.params.type)?.key;
  }
  return arr.find((v) => (v.to.params as any)?.name === route.params.name)?.key;
  // const nameItem: any = arr.find((v) => {
  //   const nameMatch = v.to.name === route.name;
  //   const paramsMatch = v.to?.params?.type === route.params.type;
  //   if (route.name === "list-type-page") {
  //     return v.to?.params?.type === route.params.type;
  //   }
  //   return true;
  //   // const paramsMatch = Object.keys(v.to?.params || {}).findIndex((attr) => {
  //   //   if (attr === "type") {
  //   //     return (v.to as any).params[attr] === route.params[attr];
  //   //   }
  //   //   return true;
  //   // });
  //   // return nameMatch && paramsMatch !== -1;
  // });
  // return nameItem?.key || menuOptions[0].key;
});

// 回首页
const goHome = () => {
  navigateTo({
    path: "/",
  });
};

// 搜索
const searchRef = ref();
const showDrawer = () => {
  searchRef.value?.open();
};

// 退出登录
const options = [
  {
    label: "用户中心",
    key: "center",
  },
  {
    label: "退出",
    key: "logout",
  },
];
const handleSelect = (key: string | number) => {
  if (key === "center") {
    navigateTo("/user/history/1");
    return;
  }
  if (key === "logout") {
    const { dialog } = createDiscreteApi(["dialog"]);
    dialog.warning({
      content: "是否要退出登录？",
      positiveText: "退出",
      negativeText: "取消",
      onPositiveClick: async () => {
        await useLogout();
      },
    });
    return;
  }
};

// 登录
const goLogin = () => {
  navigateTo("/login?from=" + route.fullPath);
  // navigateTo({
  //   name: "login",
  //   query: {
  //     redirect: encodeURIComponent(route.fullPath), // 组装登出的路径，登录时好跳转到这里
  //   },
  // });
};
</script>

<style scoped lang="scss">
.navbar {
  z-index: 1000;
  @apply bg-white fixed top-0 left-0 right-0 shadow-sm;
  display: flex;
  justify-content: space-between;
  padding: 0 40px;
}
.darkmode-toggle {
  z-index: 1001;
}
.bold {
  font-weight: 700;
}
.left,
.right {
  display: flex;
  align-items: center;
}

.right {
  align-items: center;
  cursor: pointer;
}
</style>
